<template>
  <!-- 地图 -->
  <el-row type="flex" justify="space-between" class="mapWrapper">
    <el-col :span="15">
      <div id="container" style="width: 650px; height: 360px"></div>
    </el-col>
    <el-col :span="8">
      <div class="asizeHead">
        <div
          class="navLine"
          :style="`transform: translate(${currentNum * 68}px)`"
        ></div>
        <span
          class="nav"
          v-for="(nav, index) in ['风景', '交通']"
          :key="index"
          @click="handleClick(index)"
          :class="{
            active: currentNum == index,
          }"
        >
          {{ nav }}</span
        >
      </div>
      <div class="asizeBody" v-if="currentNum == 0">
        <div
          class="rowData"
          v-for="(pois, index) in poisList"
          :key="pois.id"
          :id="'pois' + index"
          @mouseenter="authPosition(index)"
        >
          <div>{{ pois.name }}</div>
          <div>{{ pois.newDistance }}</div>
        </div>
      </div>
      <div class="asizeBody" v-if="currentNum == 1">
        <div
          class="rowData"
          v-for="(pois, index) in poisList"
          :key="pois.id"
          :id="'pois' + index"
          @mouseenter="authPosition(index)"
        >
          <div>{{ pois.name }}</div>
          <div>{{ pois.newDistance }}</div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import { Badge } from "element-ui";
export default {
  props: ["hotelInfo"],
  data() {
    return {
      currentNum: 0,
      poisList: [],
      map: {},
      markerList: [],
      markerCenter: {},
      center: "",
      MyInfoWindow: () => {},
    };
  },
  watch: {
    // 到时候需要优化
    // 监听加载高德地图
    async currentNum() {
      //   移除覆盖物在显示
      this.map.clearMap();
      //   获取周围信息数据
      //   因为this.getPoi()是异步的代码需要将其执行完在执行下面的this.loadpoi()函数
      await this.getPoi();

      // 加载点标记及绑定鼠标移入设置中心点事件
      this.loadpoi();
    },
  },
  methods: {
    // 处理周围风景或交通地点的鼠标移入事件
    authPosition(index) {
      // 鼠标移入获取对应的中心点坐标进行定位
      let newCenter = [
        this.poisList[index].location.split(",")[0],
        this.poisList[index].location.split(",")[1],
      ];

      // 设置中心点定位
      this.map.setCenter(newCenter);

      // 点标记的信息窗口的提示

      this.MyInfoWindow(index).open(this.map, newCenter);
      this.MyInfoWindow(index).setPosition(newCenter);
    },
    // 封装加载高德地图函数
    async loadMap() {
      //中心点坐标
      this.center = [
        this.hotelInfo.location.longitude,
        this.hotelInfo.location.latitude,
      ];
      let data = this.hotelInfo;

      // 发送请求获取周围数据
      let res = await this.getPoi();

      //   console.log(res.data, "res");
      // 使用箭头函数改变this指向
      window.onLoad = () => {
        this.map = new AMap.Map("container", {
          zoom: 16,
          center: this.center,
          viewMode: "3D",
          resizeEnable: true,
        });
        this.loadpoi();
      };

      var url =
        "https://webapi.amap.com/maps?v=1.4.15&key=2f8f1ab47f5f80d384d6543fe6658a6a&callback=onLoad";
      var jsapi = document.createElement("script");
      jsapi.charset = "utf-8";
      jsapi.src = url;
      document.head.appendChild(jsapi);
    },
    getPoi() {
      return this.$axios({
        url: "https://restapi.amap.com/v3/place/text",
        params: {
          keywords: "",
          city: this.hotelInfo.city.name.replace(/市$/, ""),
          location:
            this.hotelInfo.location.longitude +
            "," +
            this.hotelInfo.location.latitude,
          types: this.currentNum == 0 ? "风景名胜" : "交通设施服务",
          output: "json",
          page: 1,
          offset: 10,
          key: "37bf7f90d1c870a433d2c426467bc5fe",
        },
      }).then((res) => {
        this.poisList = res.data.pois;

        return res.data.pois;
      });
    },

    // 封装点标记生成和相关事件的绑定函数
    loadpoi() {
      AMap.plugin("[AMap.Marker,AMap.GeometryUtil,AMap.InfoWindow]", () => {
        // 获取周围10个风景 使用箭头函数改变this指向
        // 1.1 获取所有地点的坐标
        var markerCenter = new AMap.Marker({
          map: this.map, //显示的地图
          position: this.center,
          zIndex: 1000,
          animation: "AMAP_ANIMATION_DROP",
          content: `
                  <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png">
                  <span class="close-btn iconfont iconhotel "></span>
               `,
        });
        // 将酒店的点标记实例存储到data
        // this.markerCenter = markerCenter;

        // 添加酒店的点标记
        var marker = "";

        this.poisList.forEach((poisItem, index) => {
          marker = new AMap.Marker({
            // 使用title就可以实现提示
            title: poisItem.name,

            // 配置地标
            map: this.map, //显示的地图
            position: [
              poisItem.location.split(",")[0],
              poisItem.location.split(",")[1],
            ],
            content: `
                  <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png">
                  <span class="close-btn btn${index}" ">${index + 1}</span>
               `,
          });
          //   将每个生成的点标记实例加到数组
          //   this.markerList.push(marker);
          //地图自适应多个标记点 可以根据所有的点标记进行适应显示
          this.map.setFitView();

          //根据id绑定外面的dom的鼠标移入事件

          // 清空其它的鼠标移入事件

          //单独绑定中心点的 鼠标移入到标记改变地图显示的中心点
          AMap.event.addListener(markerCenter, "mouseover", (e) => {
            // marker是鼠标移入的对应的点标记 e可以获取到marker标记的事件对象

            // 获取标记的坐标 不要使用当前鼠标移入的点的位置的坐标 否则会出现提示位置偏差
            var center = [e.target.w.position.lng, e.target.w.position.lat];
            // 改变地图中心点;

            this.map.setCenter(center);

            // 鼠标移入到标记显示提示功能
            //自定义的提示结构

            var info = [];
            if (this.hotelInfo.hotellevel == null) {
              this.hotelInfo.hotellevel = {
                arrLevel: [],
              };
            }
            var str = "";
            //  将信息显示的酒店的星级的html处理好在加到info数组中
            this.hotelInfo.hotellevel.arrLevel.forEach((item) => {
              str += `<i class="iconfont iconhuangguan"></i>`;
            });

            // 将arr转化为需要的html字符串

            // var   strHtml=arr
            info.push(
              `
                      <div class="titleWrapper">
                        <div class="head">
                          <h1>${this.hotelInfo.name}</h1>
                          <div class="price">价格:￥${this.hotelInfo.price}</div>
                        </div>
                        <div class="main">
                          <img src="${this.hotelInfo.photos}" />
                          <div class="info">
                            <p>地址:${this.hotelInfo.address}</p>
                            <p>电话:${this.hotelInfo.phone}</p>
                            <span  v-if='null' class="star">
                              ${str}
                            </span> 
                          </div>
                       </div>
                     </div>
                      `
            );
            //创建信息窗口的实例
            var InfoWindow = new AMap.InfoWindow({
              //加入自定义的提示结构
              content: info.join(""),
              //设置提示显示位置的偏移量 向右2向上30
              offset: new AMap.Pixel(2, -30),
            });

            //设置打开信息窗体
            InfoWindow.open(this.map, marker.getPosition());
            //设置信息窗体显示的位置
            InfoWindow.setPosition(center);
          });
          //鼠标移入到标记改变地图显示的中心点
          AMap.event.addListener(marker, "mouseover", (e) => {
            // marker是鼠标移入的对应的点标记 e可以获取到marker标记的事件对象
            // 获取标记的坐标 不要使用当前鼠标移入的点的位置的坐标 否则会出现提示位置偏差
            var center = [e.target.w.position.lng, e.target.w.position.lat];
            // 改变地图中心点;
            this.map.setCenter(center);

            // 鼠标移入到标记显示提示功能
            //自定义的提示结构
            var info = [];
            info.push(
              `<div style="font-size: 12px;color: #333">${e.target.w.title}</div>`
            );
            //创建信息窗口的实例
            var InfoWindow = new AMap.InfoWindow({
              //加入自定义的提示结构
              content: info.join(""),
              //设置提示显示位置的偏移量 向右2向上30
              offset: new AMap.Pixel(2, -30),
            });

            //设置打开信息窗体
            InfoWindow.open(this.map, marker.getPosition());
            //设置信息窗体显示的位置
            InfoWindow.setPosition(center);
          });
        });
        console.log(this.poisList, "this.poisList");
        //创建信息窗口的实例
        this.MyInfoWindow = (index) => {
          return new AMap.InfoWindow({
            //加入自定义的提示结构
            content: [
              `<div style="font-size: 12px;color: #333">${this.poisList[index].name}</div>`,
            ].join(""),
            //设置提示显示位置的偏移量 向右2向上30
            offset: new AMap.Pixel(2, -30),
          });
        };

        this.poisList = this.poisList.map((item) => {
          //1. 计算每个点的距离
          // 中心点的坐标
          var p1 = [
            this.hotelInfo.location.longitude,
            this.hotelInfo.location.latitude,
          ];
          //其它点标记点的坐标
          var p2 = [item.location.split(",")[0], item.location.split(",")[1]];
          //计算两点间的距离 转化未公里单位的值
          var mapLength = (AMap.GeometryUtil.distance(p1, p2) / 1000).toFixed(
            2
          );

          return {
            ...item,
            newDistance: mapLength + "公里",
          };
        });
      });
    },

    handleClick(index) {
      this.currentNum = index;
    },
  },
  mounted() {
    // 发送请求获取酒店数据且加载高德地图
    this.loadMap();
  },
};
</script>

<style lang="less" scoped>
.mapWrapper {
  margin-top: 40px;
  margin-bottom: 20px;
  /deep/.amap-info-content {
    .titleWrapper {
      border: 1px solid #e4e4e4;
      .head {
        background-color: #f9f9f9;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-top: 4px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e4e4e4;
        h1 {
          font-size: 16px;
          margin-right: 10px;
          margin-left: 4px;
        }
        .price {
          width: 100px;
          color: #f00;
          font-size: 14px;
          font-weight: 600;
        }
      }
      .main {
        padding: 10px 4px;
        display: flex;
        img {
          margin-right: 8px;
          width: 114px;
          height: 72px;
        }
        .info {
          color: #666;
          font-size: 14px;

          .star {
            display: flex;
            .iconhuangguan {
              color: #ff9900;
            }
          }
        }
      }
    }
  }

  /deep/ .amap-marker {
    // border: 1px solid #000;
    .amap-marker-content {
      width: 22px;
      height: 36px;

      display: flex;

      img {
        display: block;
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
      }
      span {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0px;
        left: 0px;
        display: block;
        text-align: center;
      }
    }
  }
  .asizeHead {
    position: relative;
    display: flex;
    height: 40px;
    border-bottom: 2px solid #e4e4e4;

    .active {
      color: #409eff;
    }
    .navLine {
      position: absolute;
      bottom: -2px;
      height: 1px;
      width: 28px;
      background-color: #409eff;
      transition: all 0.3s cubic-bezier(0.65, 0.05, 0.36, 1);
    }
    .nav {
      font-size: 14px;
      cursor: pointer;
      display: block;
      width: 28px;
      margin-right: 40px;
      padding: 10px 0;
      padding-bottom: 11px;
    }
  }
  .asizeBody {
    height: 300px;
    margin-top: 16px;
    //   border: 1px solid #000;
    color: #666;
    padding-left: 10px;
    padding-right: 16px;
    font-size: 14px;
    overflow-y: scroll;
    .rowData {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;
      cursor: pointer;
      > div:first-child {
        flex: 1;
      }
      > div:last-child {
        padding-right: 10px;
      }
    }
  }
}
</style>